package com.happymmall.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    // MD5加密
    public static String md5Encode(String str) {
        // 增加非空校验：如果str为null，直接返回null或空字符串
        if (str == null) {
            return null; // 或 return ""; 根据业务需求决定
        }

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] byteArray = str.getBytes(); // 这里之前因为str为null报错
            byte[] md5Bytes = md5.digest(byteArray);

            StringBuilder hexValue = new StringBuilder();
            for (byte md5Byte : md5Bytes) {
                int val = ((int) md5Byte) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
